<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use EasyDingTalk\Application;

class DingTalkSync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dingtalk:sync {action?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * dingtalk app
     * 
     * @var EasyDingTalk\Application
     */
    protected $app;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $config = [
            'corp_id' => config('dingtalk.corp_id'),
            'app_key' => config('dingtalk.app_key'),
            'app_secret' => config('dingtalk.app_secret'),
            'token' => config('dingtalk.token'),
            'aes_key' => config('dingtalk.aes_key')
        ];
        $this->app = new Application($config);

        $action = $this->argument('action');
        switch ($action) {
            case "deps+users":
            case "deps":
            case "users":
                $this->syncDeptAndUser();
                break;
            case "setCallBack":
                $this->registerCallBack();
                break;
            case 'getCallBack':
                $this->getCallBack();
                break;
            default:
                $this->info('请输入对应的action:[users,setCallBack]');
        }
        return 0;
    }

    /**
     * test
     */
    function test($message)
    {
        echo "test:" . $message . "\n";
    }

    /**
     * 获取消息回调信息
     */
    public function getCallBack()
    {
        $callbackList = $this->app->callback->list();
        // var_dump($callbackList);
        if (isset($callbackList['errcode']) && $callbackList['errcode'] == 0) {
            $call_back_tag = isset($callbackList['call_back_tag']) ? json_encode($callbackList['call_back_tag']) : "[]";
            $url = isset($callbackList['url']) ? $callbackList['url'] : "";
            $this->info("url:\t" . $url);
            $this->info("call_back_tag:\t" . $call_back_tag);
        } else if (isset($callbackList['errmsg'])) {
            $this->error($callbackList['errmsg']);
        }
    }

    /**
     * 注册消息回调
     * 
     */
    public function registerCallBack()
    {
        $params = [
            'call_back_tag' => [
                "user_add_org",
                "user_modify_org",
                "user_leave_org",
                "user_active_org",
                "org_admin_add",
                "org_admin_remove",
                "org_dept_create",
                "org_dept_modify",
                "org_dept_remove",
                "org_remove",
                "org_change"
                // 'label_user_change',
                // 'label_conf_add',
                // 'label_conf_del',
                // 'label_conf_modify'
            ],
            'url' => "http://infosys.shixunsuda.com/dingding/callback"
        ];
        $resp = $this->app->callback->register($params);
        if (isset($resp['errcode']) && $resp['errcode'] == 0) {
            $this->info($resp['errmsg']);
        } else if (isset($resp['errmsg'])) {
            $this->error($resp['errmsg']);
        }
    }

    /**
     * 获取部门及部门下的员工信息
     */
    public function syncDeptAndUser()
    {
        $departments = $this->app->department->list(1);
        if (!$departments || !isset($departments["department"]) || count($departments["department"]) <= 0) {
            echo "没有发现部门列表";
            return 0;
        }
        foreach ($departments["department"] as $index => $department) {
            echo $department['name'] . "\n";
            $this->getDetailedUsers($department['id'], 1);
            $this->getDepartmentLoop($department['id'], 1);
        }
    }

    /**
     * 循环获取部门信息
     */
    public function getDepartmentLoop($parent_id, $deep)
    {
        $subIds = $this->app->department->getSubDepartmentIds($parent_id);
        if (!isset($subIds["sub_dept_id_list"]) || count($subIds["sub_dept_id_list"]) <= 0) {
            // echo str_repeat("\t", $deep). "没有子部门\n";
            return 0;
        }
        foreach ($subIds["sub_dept_id_list"] as $subId) {
            $departmentInfo = $this->app->department->get($subId);
            echo str_repeat("  ", $deep) . $departmentInfo['name'] . "\n";
            //var_dump($departmentInfo);
            $this->getDetailedUsers($subId, $deep + 1);
            $this->getDepartmentLoop($subId, $deep + 1);
        }
    }

    /**
     * 获取用户的详细信息
     */
    public function getDetailedUsers($departmentId, $deep, $offset = 0, $size = 100)
    {
        $users = $this->app->user->getDetailedUsers($departmentId, $offset, $size);
        if (!isset($users['userlist']) || count($users['userlist']) <= 0) {
            return 0;
        }
        foreach ($users['userlist'] as $user) {
            echo str_repeat("  ", $deep) . $user['name'] . "\n";
        }
    }
}
